from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models

from common.logger import log
from . import sms_settings
import json
import random


# 获取四位随机验证码
def get_code():
    s_code = ''
    for i in range(4):
        s_code += str(random.randint(0,9))
    return s_code


# 发送短信 ，腾讯短信验证码sdk 3.0
def send_message(telephone, code):
    try:
        telephone = f'+86{telephone}'

        # 实例化认证对象，传入腾讯云账户密钥对
        # https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential(sms_settings.secretId,
                                     sms_settings.secretKey)

        # 实例化要请求产品(以sms为例)的client对象，没有实例化客户端配置对象，就不需要传clientProfile
        # client = sms_client.SmsClient(cred, "ap-guangzhou",clientProfile)
        # 第二个参数是地域信息，可以直接填写字符串ap-guangzhou，支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
        client = sms_client.SmsClient(cred, "ap-guangzhou")

        # 实例化一个请求对象，根据调用的接口和实际情况，可以进一步设置请求参数
        req = models.SendSmsRequest()

        params = {
            "PhoneNumberSet": [telephone, ],  # 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
            "SmsSdkAppId" : sms_settings.appid,  # 短信应用ID
            "SignName" : sms_settings.sms_sign,  # 短信签名内容
            "TemplateId" : sms_settings.template_id,  # 模板 ID
            "TemplateParamSet" : [code, sms_settings.Exp_interval], # 模板参数
        }

        req.from_json_string(json.dumps(params))
        resp = client.SendSms(req)

        if resp:
            return True
        else:
            return False

    except TencentCloudSDKException as err:
        log.error(f'手机号：{telephone}验证码发送失败，错误为：{str(err)}')
